using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using T2V.SharePoint.Common.Utilities;
using PepsiCo.Common;
using T2V.SharePoint.Common.Helpers;
using T2V.SharePoint.Common.Models;
using T2V.SharePoint.Common.Extensions;
using System.Linq;
using Microsoft.SharePoint.Utilities;
using System.IO;
using Microsoft.SharePoint.Publishing;
using System.Reflection;

namespace PepsiCo.Intranet.Features.PepsiCo.Web
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("88c07821-9cfb-4ab3-8450-f2a70779705d")]
    public class PepsiCoWebEventReceiver : SPFeatureReceiver
    {
        // Uncomment the method below to handle the event raised after a feature has been activated.

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            var web = properties.Feature.Parent as SPWeb;

            PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(web);
            publishingWeb.Navigation.GlobalIncludePages = false;
            publishingWeb.Navigation.CurrentIncludePages = false;
            publishingWeb.Update();

            bool tempAllowUnsafeUpdates = web.AllowUnsafeUpdates;

            //set all publishing pages to BlankWebPartPage.aspx
            web.AllowUnsafeUpdates = true;
            try
            {
                var listPages = web.Lists.TryGetList("Pages");
                if (listPages!= null)
                {
                    SPContentType pageCT = listPages.ContentTypes["Page"];
                    if (pageCT != null)
                    {
                        listPages.ContentTypes.Delete(pageCT.Id);
                    }

                    SPContentType articlePageCT = listPages.ContentTypes["Article Page"];
                    if (articlePageCT != null)
                    {
                        listPages.ContentTypes.Delete(articlePageCT.Id);
                    }

                    listPages.EnableVersioning = true;
                    listPages.EnableMinorVersions = false;
                    listPages.ForceCheckout = false;
                    listPages.Update();
                }

                PageLayout[] layouts = publishingWeb.GetAvailablePageLayouts();
                PageLayout layout = layouts[0];
                var publishingPages = publishingWeb.GetPublishingPages();
                foreach (PublishingPage page in publishingPages)
                {
                    if (page.Url.Contains("default.aspx") == true)
                    {
                        page.CheckOut();
                        page.Layout = layout;
                        page.Title = "Introduction";
                        page.Update();
                        page.CheckIn("");
                    }
                }
           

                //UpdateNewsCategoroySettings(web);
                //CreateFirstCategory(web);
                var listNews = Utility.GetListFromURL(PepsiCoConstants.NEWS_LIST_URL, web);
                if (listNews != null)
                {
                    CreateDetailNewsPage(web, listNews);
                    UpdateImageField(web, listNews, "NewsImages");
                    CreateNewsListView(web, listNews);
                }
                var listContactInfomation = Utility.GetListFromURL(PepsiCoConstants.CONTACT_INFORMATION_LIST_URL, web);
                if (listContactInfomation != null)
                {
                    UpdateImageField(web, listContactInfomation, "ContactImages");
                }

                var listLinks = Utility.GetListFromURL(PepsiCoConstants.LINKS_LIST_URL, web);
                if (listLinks != null)
                {
                    UpdateImageField(web, listLinks, "LinkImages");
                }

                var listModernUI = Utility.GetListFromURL(PepsiCoConstants.Tile.LIST_URL, web);
                if (listModernUI != null)
                {
                    UpdateImageField(web, listModernUI, "PublishingImages");
                }

                //Provision WebPart
                ProvisionWebpart(web, "PepsiCo.Intranet.XMLCustomSettings.Webparts.xml");

                //Permission
                string adminGroup = web.Title.TrimEnd() + " Owners";
                web.CreateNewGroup(adminGroup, adminGroup, SPRoleType.Administrator);
                string memberGroup = web.Title.TrimEnd() + " Members";
                web.CreateNewGroup(memberGroup, memberGroup, SPRoleType.Contributor);
                string visitorGroup = web.Title.TrimEnd() + " Visitors";
                web.CreateNewGroup(visitorGroup, visitorGroup, SPRoleType.Reader);
                //Add exits group
                //var restrictedReader = web.SiteGroups.Cast<SPGroup>().FirstOrDefault(p => p.Name == "Restricted Readers");
                //if (restrictedReader != null)
                //{
                //    SPRoleDefinition roleDefinition = web.RoleDefinitions["Restricted Read"];
                //    web.AddExistedGroup("Restricted Readers", roleDefinition);
                //}

                //string templateFilename = "_webpartpage.htm";
                //string hive = SPUtility.GetGenericSetupPath("TEMPLATE\\1033\\STS\\DOCTEMP\\SMARTPGS\\");
                //using (FileStream stream = new FileStream(hive + templateFilename, FileMode.Open))
                //{
                //    SPList listPages = web.Lists.TryGetList("Pages");
                //    SPFolder subFolder = listPages.RootFolder.SubFolders["Forms"];
                //    SPFile file = subFolder.Files.Add(subFolder.Url + "/" + templateFilename, stream, true);

                //    SPDocumentLibrary docPages = listPages as SPDocumentLibrary;
                //    docPages.DocumentTemplateUrl = "Pages/Forms/_webpartpage.htm";
                //    docPages.Update();
                //}

            }
            catch (Exception ex)
            { }
            finally
            {
                web.AllowUnsafeUpdates = tempAllowUnsafeUpdates;
            }
        }

        private void CreateDetailNewsPage(SPWeb web, SPList list)
        {
            var rootFolder = list.RootFolder;

            var dispFormUrl = string.Format("{0}/{1}/{2}.aspx", web.ServerRelativeUrl.TrimEnd('/'), rootFolder.Url, PepsiCoConstants.NEWS_DISPLAYPAGE);
            var dispForm = web.GetFile(dispFormUrl);
            if (dispForm != null && dispForm.Exists)
                dispForm.Delete();	// delete & recreate our display form

            // create a new DispForm
            dispForm = rootFolder.Files.Add(dispFormUrl, SPTemplateFileType.FormPage);

            WebPartHelper.ProvisionWebpart(web, new WebpartPageDefinitionCollection()
            {
                new WebpartPageDefinition() {
                PageUrl = dispForm.Url,
                Title = list.Title,
                Webparts = new System.Collections.Generic.List<WebpartDefinition>() {
                        new DefaultWP(){
                            Index = 0,
                            ZoneId = "Main",
                            WebpartName = "NewsDetailView.webpart",
                            Properties = new System.Collections.Generic.List<Property>(){
                                new Property(){
                                    Name = "Title",
                                    Value = list.Title
                                },
                                new Property(){
                                    Name="ChromeType",
                                    Type="chrometype",
                                    Value="2"
                                }
                            }
                        }
                    }
                },
                new WebpartPageDefinition() {
                PageUrl = dispForm.Url,
                Title = "Other news",
                Webparts = new System.Collections.Generic.List<WebpartDefinition>() {
                        new DefaultWP(){
                            Index = 2,
                            ZoneId = "Main",
                            WebpartName = "OtherNewsListView.webpart",
                            Properties = new System.Collections.Generic.List<Property>(){
                                new Property(){
                                    Name = "Title",
                                    Value = "Other news"
                                }
                            }
                        }
                    }
                }
            });

            dispForm.Update();
            //list.Update();
        }

        private void UpdateImageField(SPWeb web, SPList list, string pictureLibraryUrl)
        {
            try
            {
                var fields = list.Fields.Cast<SPField>().ToList();
                var imageFields = fields.Where(p => p.TypeAsString == PepsiCoConstants.IMAGE_FIELD_TYPE_NAME).ToList();
                foreach (var item in imageFields)
                {
                    //var currentWeb = item.ParentList.ParentWeb;
                    //var newsImageLibrary = web.Lists[web.Folders["NewsImages"].ParentListId];
                    var newsImageLibrary = Utility.GetListFromURL(pictureLibraryUrl, web);

                    item.UpdateImageField(web, newsImageLibrary);
                }
            }
            catch (Exception ex)
            {
                
            }
        }

        private void CreateNewsListView(SPWeb web, SPList list)
        {
            try
            {
                // create new view with custom webpart
                SPViewCollection allviews = list.Views;
                string viewName = PepsiCoConstants.NEWS_LISTPAGE;

                System.Collections.Specialized.StringCollection viewFields = new System.Collections.Specialized.StringCollection();

                var view = allviews.Add(viewName, viewFields, string.Empty, 1, true, true);
                WebPartHelper.HideXsltListViewWebParts(web, view.Url);
                WebPartHelper.ProvisionWebpart(web, new WebpartPageDefinitionCollection()
                {
                    new WebpartPageDefinition() {
                    PageUrl = view.Url,
                    Title = list.Title,
                    Webparts = new System.Collections.Generic.List<WebpartDefinition>() {
                            new DefaultWP(){
                                Index = 0,
                                ZoneId = "Main",
                                WebpartName = "NewsListView.webpart"
                            }
                        }
                    }
                });
                WebPartHelper.MoveWebPart(web, view.Url, "NewsListView.webpart", "Main", 0);
                view.Title = "Approved Items";
                view.Update();
                //list.Update();
            }
            catch (Exception ex)
            {
                
            }
        }

        private void ProvisionWebpart(SPWeb web, string xmlFile)
        {
            try
            {
                Assembly assembly = Assembly.GetExecutingAssembly();
                string xml = assembly.GetResourceTextFile(xmlFile);

                var webpartPage = SerializationHelper.DeserializeFromXml<WebpartPageDefinitionCollection>(xml);

                WebPartHelper.ProvisionWebpart(web, webpartPage);
            }
            catch (Exception ex)
            {
                
            }
        }

        // Uncomment the method below to handle the event raised before a feature is deactivated.

        //public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised after a feature has been installed.

        //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised before a feature is uninstalled.

        //public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        //{
        //}

        // Uncomment the method below to handle the event raised when a feature is upgrading.

        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}
    }
}
